package com.inepex.inegraphics.impl.client;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.inepex.inegraphics.impl.client.IncrementallyUpdatable.IncrementalUpdater;

/**
 * Base implementation for scheduled (incremental) processes.
 * It starts its progress immediately after instantiation.
 * 
 * @author Miklos Suveges
 *
 */
public abstract class IncrementalUpdaterImpl implements IncrementalUpdater {
	
	protected int partTreshold;
	protected IncrementallyUpdatable target;
	protected boolean isReady = false;
	
	protected class CommandImpl implements RepeatingCommand{

		@Override
		public boolean execute() {
			boolean inProgress = IncrementalUpdaterImpl.this.target.nextUpdatePart();
			if(!inProgress){
				onFinished();					
			}
			return inProgress;
		}
		
	}
		
	public IncrementalUpdaterImpl(IncrementallyUpdatable target) {
		this(target, 40);
	}

	public IncrementalUpdaterImpl(IncrementallyUpdatable target, int partTreshold) {
		target.initUpdate(this);
		this.partTreshold = partTreshold;
		this.target = target;
		Scheduler.get().scheduleIncremental(new CommandImpl());
	}

	@Override
	public int getUpdatePartTresholdMS() {
		return partTreshold;
	}

	/**
	 * Implement this method to be notified when the progress is complete. 
	 */
	public abstract void onFinished();
}
